package com.example.shirodemo.framework.shiro.realm;

import com.demo.bean.User;
import com.example.shirodemo.framework.shiro.exception.AuthorizationInfoException;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * Created on 2018/10/8
 *
 * @author Saligia
 */
@Slf4j
public class SsoRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 构造授权信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //当前登录用户拥有的角色
        simpleAuthorizationInfo.setRoles(Sets.newHashSet("admin", "manager"));
        //当前登录用户拥有的权限标识
        simpleAuthorizationInfo.setStringPermissions(Sets.newHashSet("user/add", "user/edit", "user/info"));
//        if (true) {
//            throw new AuthorizationInfoException("权限信息获取异常");
//        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        //此处异常均被封装为AuthenticationException；错误信息 = e.getCause().getMessage();
        User user = new User("张三", "11111");
//        if ("11111".equals(user.getPassword())) {
//            throw new RuntimeException("登录异常：用户为空");
//        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
